<?php
declare (strict_types=1);

namespace app\index\controller;

use app\common\model\OrderTemporary;
use app\common\model\Product as ProductModel;
use app\common\model\ProductSpec;
use app\common\model\ProductCart;
use app\common\tool\Result;
use think\facade\Cache;
use think\facade\View;
use think\Response;

class Product extends Base
{

    public function search()
    {
        $history = Cache::get('searchHistory_' . $this->user->id);
        if ($history) {
            $history = json_decode($history, true);
            $news = [];
            for ($i = count($history); $i > 0; $i--) {
                $news[] = $history[$i - 1];
            }
            $history = $news;
        }
        View::assign('history', $history ?: []);
        return View::fetch();
    }

    public function emptySearch()
    {
        Cache::delete('searchHistory_' . $this->user->id);
        return Result::success('已清空');
    }


    public function index()
    {
        $cate_1 = $this->request->get('cate_1');
        $cate_2 = $this->request->get('cate_2');
        $keyword = $this->request->get('keyword');
        View::assign([
            'keyword' => $keyword,
            'query'   => urlencode('cate_1=' . $cate_1 . '&cate_2=' . $cate_2 . '&keyword=' . $keyword)
        ]);
        return View::fetch();
    }

    public function details($id)
    {
        $info = ProductModel::where(['status' => 1, 'id' => $id])->find();
        if (empty($info)) return redirect('/');
        $info->images = explode(',', $info->images);
        $info->spec = $info->spec ? json_decode($info->spec, true) : '';
        return View::fetch('', [
            'info'  => $info,
            'count' => ProductCart::where('uid', $this->user->id)->sum('num')
        ]);
    }


    public function getList(): Response
    {
        $param = $this->request->get();
        $map = [];
        foreach ($param as $key => $value) {
            if (!in_array($key, ['page', 'type', 'keyword']) && $value) {
                $map[$key] = $value;
            }
        }
        $like = [];
        if (isset($param['keyword']) && $param['keyword']) {
            $like['field'] = 'title';
            $like['keyword'] = $param['keyword'];
            $history = Cache::get('searchHistory_' . $this->user->id);
            if ($history) {
                $history = json_decode($history, true);
                if (!in_array($param['keyword'], $history)) {
                    $history[] = $param['keyword'];
                    if (count($history) > 10) {
                        unset($history[0]);
                    }
                    Cache::set('searchHistory_' . $this->user->id, json_encode($history));
                }
            } else {
                $history[] = $param['keyword'];
                Cache::set('searchHistory_' . $this->user->id, json_encode($history));
            }
        }
        return Result::fastReturn(
            ProductModel::getPageList($map, 'id,title,price,vip_price,icon,sales', $param['page'], 20, true, '', '', ['key' => 'sort', 'value' => 'asc'], $like));
    }

    public function getSpecPrice($pid, $spec): Response
    {
        try {
            $specValue = ProductSpec::where(['pid' => $pid, 'merge_title' => $spec])->find();
            if (empty($specValue)) {
                return Result::fail('当前规格已下架！');
            }
            return Result::success('success', $specValue);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }

    public function submit(): Response
    {
        $param = $this->request->post();
        $param['type'] = 1;
        return Result::fastReturn(OrderTemporary::setTemporary($param, $this->user));
    }
}

